'use strict';
/**
 * Created by FreezeSoul on 2015/10/16.
 */
define([
        'angular',
        'app/modules/schema/define',
        'app/modules/schema/services/schema-tree'
    ],
    function(angular) {
        angular.module('ad.schema')
            .directive('uniqueSchemaCode', ['$q','adSchemaTreeService',
                function($q,server) {
                    return {
                        require: 'ngModel',
                        link: function(scope, elm, attrs, ctrl) {

                            ctrl.$asyncValidators.schema_code_unique = function(modelValue, viewValue) {
                                if (ctrl.$isEmpty(modelValue)) {
                                    return $q.when();
                                }

                                var def = $q.defer();
                                var id = scope.item.schema_id;
                                var code = modelValue;
                                server.checkSchemaCode(id,code).then(function(data){
                                    var obj = angular.fromJson(data);
                                    if(obj.result == 'success'){
                                        def.resolve();
                                    }else{
                                        def.reject();
                                    }

                                },function(state){
                                });

                                return def.promise;
                            };
                        }
                    };
                }
            ]);
    });